<?php

namespace Modules\Entity\Controllers;

use Core\Mvc\Controller;
use Core\Paginator\Adapter\Collection as CollectionPaginator;
use Modules\Entity\Library\Entity;
use MongoDB\BSON\ObjectID;

class AdminController extends Controller
{

    public function indexAction($entity, $page)
    {
        // 获取实体类型
        $entityList = $this->config->cache('entity');
        if (!isset($entityList[$entity]) || $entityList[$entity]['page']['adminIndex'] == false) {
            return false;
        }

        $entityInfo = $entityList[$entity];
        $query = [
            'sort' => [
                'changed' => -1,
            ],
            'limit' => 30,
            'skip' => 30 * ($page - 1),
        ];
        $filterForm = false;
        $handleForm = false;
        $menuTabs = false;
        $content = [];

        /*
         * proccess filter form
         */
        if (isset($entityInfo['filterForm'])) {
            $filterInfo = $this->config->get($entityInfo['filterForm']);
            //$this->config->printCode($filterInfo);
            $filterInfo['_options'] += [
                '_entity' => $entity,
                '_page' => $page,
                '_query' => $query,
            ];
            $filterForm = $this->form->create($filterInfo);
            if ($filterForm->isValid()) {
                $filterSave = $filterForm->save();
                if ($filterSave !== false) {
                    $query = $filterSave;
                }
            }
        }
        /*
         * end process filter form
         */

        $contentModelList = $this->entityManager->contentModel($entity);

        /*
         * process handle form
         */
        if (isset($entityInfo['handleForm'])) {
            $handleForm = $this->form->create($entityInfo['handleForm']);
            if ($handleForm->isValid()) {
                $handleForm->save();
            }
        }
        /*
         * end process handle form
         */

        /*
         * process menuTabs
         */
        if (isset($entityInfo['menuTabs'])) {
            if (isCallable($entityInfo['menuTabs'])) {
                $menuTabs = $entityInfo['menuTabs'](['entity' => $entity, 'query' => $query]);
            }
        }

        $data = $this->entityManager->find($entity, $query);
        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => $entityInfo['class'],
        ]);
        $label = $entityInfo['name'];
        self::$variables += array(
            'title' => '实体',
            'contentModelList' => $contentModelList,
            'description' => $label . '列表',
            'params' => self::$variables['router_params'],
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'nodeList' => array(
                    'name' => $label . '列表',
                ),
            ),
            'content' => &$content,
        );

        if ($filterForm) {
            $content['filter'] = array(
                '#templates' => 'box',
                'max' => false,
                'color' => 'widget',
                'hiddenTitle' => false,
                'size' => '12',
                'wrapper' => true,
                'content' => array(
                    'filterForm' => $filterForm !== false ? $filterForm->renderForm() : $filterForm,
                ),
            );
        }
        $content['nodeList'] = array(
            'menuGroup' => isset($menuTabs) && $menuTabs ? $menuTabs : [],
            'list' => array(
                '#templates' => array(
                    'adminEntityList',
                    'adminEntityList-' . $entity,
                ),
                '#module' => $entityInfo['module'],
                'data' => $dataPagination->getPaginate(),
                'handleForm' => $handleForm,
            ),
        );
    }

    public function addAction($entity, $contentModel)
    {
        $entityObject = $this->entityManager->get($entity);
        $entityInfo = $this->entityManager->info($entity);
        $contentModelList = $this->entityManager->contentModel($entity);
        $contentModelInfo = $contentModelList[$contentModel];
        $entityEditForm = $entityObject->setContentModel($contentModel)->setField()->addForm();

        if ($entityObject->getSaveState() === true) {
            $this->flashSession->success('保存成功');
            return $this->temMoved([
                'for' => 'adminEntityList',
                'entity' => $entity,
                'page' => 1,
            ]);
        } elseif ($entityObject->getSaveState() === false) {
            $this->flashSession->error('保存失败');
        }

        $label = '添加' . $contentModelInfo['name'];

        self::$variables += array(
            'title' => $entityInfo['name'],
            'description' => $label,
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'adminEntityList' => array(
                    'href' => [
                        'for' => 'adminEntityList',
                        'entity' => $entity,
                        'page' => 1,
                    ],
                    'name' => $entityInfo['name'],
                ),
                'adminEntityAdd' => [
                    'name' => $label,
                ],
            ),
            'content' => array(
                'entityForm' => array(
                    '#templates' => [
                        'adminEntityForm',
                        'adminEntityForm-' . $entity,
                        'adminEntityForm-' . $entity . '-' . $contentModel,
                    ],
                    '#module' => $contentModelInfo['module'],
                    'data' => $entityEditForm,
                ),
            ),
        );
    }

    public function editAction($entity, $id)
    {
        $entityObject = $this->entityManager->get($entity, [
            'conditions' => [
                '_id' => new ObjectID($id),
            ],
        ]);
        $contentModelList = $this->entityManager->contentModel($entity);
        $contentModelInfo = $contentModelList[$entityObject->getContentModel()];
        $entityEditForm = $entityObject->editForm();
        if ($entityObject->getSaveState() === true) {
            $this->flashSession->success('保存成功');
            return $this->temMoved(['for' => 'adminEntityList', 'entity' => $entity, 'page' => 1]);
        } elseif ($entityObject->getSaveState() === false) {
            $this->flash->error('保存失败');
        }

        $label = '编辑' . $contentModelInfo['name'];

        self::$variables += array(
            'title' => $label,
            'description' => $entityObject->getTitle(),
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'adminAddNode' => array(
                    'name' => $label,
                ),
            ),
            'content' => array(
                'entityForm' => array(
                    '#templates' => [
                        'adminEntityForm',
                        'adminEntityForm-' . $entity,
                        'adminEntityForm-' . $entity . '-' . $entityObject->getContentModel(),
                    ],
                    '#module' => $contentModelInfo['module'],
                    'data' => $entityEditForm,
                ),
            ),
        );
    }

    public function deleteAction($entity, $id)
    {
        $entityModel = $this->entityManager->get($entity, [
            'conditions' => [
                '_id' => new ObjectID($id),
            ],
        ]);
        if (!$entityModel) {
            $this->flashSession->error('删除失败，数据不存在');
            return $this->temMoved();
        }
        $entityList = $this->config->cache('entity');
        $entityInfo = $entityList[$entity];
        if (!isset($entityInfo['page']['adminDelete']) || $entityInfo['page']['adminDelete'] === false) {
            return $this->notFount();
        }
        if ($entityModel->delete() !== false) {
            $this->flashSession->success('删除成功');
        } else {
            $this->flashSession->error('删除失败');
        }
        return $this->moved(array('for' => 'adminEntityList', 'entity' => $entity, 'page' => 1));
    }

    public function infoListAction($entity)
    {
        $entityList = $this->config->cache('entity');
        if(!isset($entityList[$entity])){
            return false;
        }
        $content = [];

        $contentModelList = $this->entityManager->contentModel($entity);

        $menu = [];
        foreach ($entityList as $t => $value) {
            $menu[$t] = [
                'href' => [
                    'for' => 'adminEntityInfoList',
                    'entity' => $t,
                ],
                'name' => $value['name'],
            ];
            if ($t == $entity) {
                $menu[$t]['active'] = true;
            }
        }

        self::$variables['title'] = '实体列表';
        self::$variables['description'] = '编辑实体信息';
        self::$variables += array(
            '#templates' => 'page',
            'breadcrumb' => array(
                'module' => array(
                    'name' => '实体列表',
                ),
            ),
            'content' => &$content,
        );
        $content['themeFilter'] = [
            '#templates' => 'menuTabs',
            'title' => '筛选实体',
            'data' => $menu
        ];
        $content['ConfigList'] = array(
            '#templates' => 'box',
            'title' => '实体列表',
            'max' => false,
            'color' => 'primary',
            'size' => '6',
            'wrapper' => true,
            'content' => array(
                'dataList' => array(
                    '#templates' => 'entityListTable',
                    '#module' => 'entity',
                    'theadDisplay' => true,
                    'thead' => [],
                    'checkAll' => false,
                    'data' => Entity::toClass($entity,$contentModelList),
                ),
            ),
        );
        $content['entityHandle'] = array(
            '#templates' => array(
                'box',
                'box-right',
            ),
            'id' => 'right_handle',
            'title' => '操作区',
            'wrapper' => true,
            'max' => true,
            'color' => 'success',
            'size' => '6',
            'content' => array(),
        );
    }

    public function infoEditAction($entity,$contentModel)
    {
        $content = [];
        $entityList = $this->config->cache('entity');
        if (!isset($entityList[$entity])) {
            return $this->notFount();
        }
        $contentModelList = $this->entityManager->contentModel($entity);
        if(!isset($contentModelList[$contentModel])){
            return $this->notFount();
        }
        $contentModelInfo = $contentModelList[$contentModel];
        $contentModelInfo['entity'] = $entity;
        $contentModelInfo['id'] = $contentModel;

        $entityEditForm = $this->form->create('entity.contentModelForm', $contentModelInfo);

        if ($entityEditForm->isValid()) {
            if ($entityEditForm->save()) {
                $this->flash->success('保存成功');
            } else {
                $this->flash->error('保存失败');
            }

            return $this->temMoved([
                'for' => 'adminEntityInfoList',
                'entity' => $entity
            ]);
        }
        self::$variables['title'] = '编辑 ' . $entityList[$entity]['name'];
        self::$variables['description'] = '';
        self::$variables += array(
            '#templates' => 'pageNoWrapper',
            'content' => &$content,
        );

        $content['termHandle'] = array(
            '#templates' => array(
                'box',
                'box-right',
            ),
            'id' => 'right_handle',
            'title' => '编辑 ' . $entityList[$entity]['name'],
            'wrapper' => false,
            'max' => true,
            'color' => 'success',
            'size' => '12',
            'content' => array(
                'termList' => $entityEditForm->renderForm(),
            ),
        );
    }
}
